package com.vibeplayer.app.fragment;

import android.content.Context;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.media.audiofx.BassBoost;
import android.media.audiofx.Equalizer;
import android.media.audiofx.Virtualizer;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.preference.PreferenceManager;

import com.h6ah4i.android.widget.verticalseekbar.VerticalSeekBar;
import com.vibeplayer.app.MainActivity;
import com.vibeplayer.app.R;
import com.vibeplayer.app.service.MusicPlayerService;

import java.util.ArrayList;
import java.util.List;

public class EqualizerFragment extends Fragment {

    private static final String PREF_EQUALIZER_ENABLED = "equalizer_enabled";
    private static final String PREF_EQUALIZER_PRESET = "equalizer_preset";
    private static final String PREF_BASS_BOOST = "bass_boost";
    private static final String PREF_VIRTUALIZER = "virtualizer";
    private static final String PREF_CUSTOM_BANDS = "custom_bands_";

    private Switch switchEqualizer;
    private Spinner spinnerPresets;
    private LinearLayout equalizerContainer;
    private SeekBar seekBarBassBoost;
    private SeekBar seekBarVirtualizer;
    private Button btnResetEqualizer;

    private Equalizer equalizer;
    private BassBoost bassBoost;
    private Virtualizer virtualizer;

    private boolean isEqualizerEnabled;
    private int currentPreset = 0;
    private short bassBoostStrength = 0;
    private short virtualizerStrength = 0;
    private short[] customBandLevels;

    private SharedPreferences preferences;
    private MediaPlayer mediaPlayer;
    private int audioSessionId = 0;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_equalizer, container, false);

        // 初始化控件
        switchEqualizer = view.findViewById(R.id.switchEqualizer);
        spinnerPresets = view.findViewById(R.id.spinnerPresets);
        equalizerContainer = view.findViewById(R.id.equalizerContainer);
        seekBarBassBoost = view.findViewById(R.id.seekBarBassBoost);
        seekBarVirtualizer = view.findViewById(R.id.seekBarVirtualizer);
        btnResetEqualizer = view.findViewById(R.id.btnResetEqualizer);

        // 获取SharedPreferences
        preferences = PreferenceManager.getDefaultSharedPreferences(requireContext());

        // 获取音频会话ID
        if (getActivity() instanceof MainActivity) {
            MainActivity activity = (MainActivity) getActivity();
            if (activity.isServiceBound() && activity.getMusicService() != null) {
                MusicPlayerService musicService = activity.getMusicService();
                if (musicService.getMediaPlayer() != null) {
                    mediaPlayer = musicService.getMediaPlayer();
                    audioSessionId = mediaPlayer.getAudioSessionId();
                    setupEqualizer();
                } else {
                    showToast("媒体播放器未初始化");
                }
            } else {
                showToast("音乐服务未绑定");
            }
        }

        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        releaseEqualizer();
    }

    private void setupEqualizer() {
        if (audioSessionId == 0) {
            showToast("无法获取音频会话ID");
            return;
        }

        try {
            // 创建均衡器
            equalizer = new Equalizer(0, audioSessionId);
            bassBoost = new BassBoost(0, audioSessionId);
            virtualizer = new Virtualizer(0, audioSessionId);

            // 加载设置
            isEqualizerEnabled = preferences.getBoolean(PREF_EQUALIZER_ENABLED, false);
            currentPreset = preferences.getInt(PREF_EQUALIZER_PRESET, 0);
            bassBoostStrength = (short) preferences.getInt(PREF_BASS_BOOST, 0);
            virtualizerStrength = (short) preferences.getInt(PREF_VIRTUALIZER, 0);

            // 设置均衡器开关
            switchEqualizer.setChecked(isEqualizerEnabled);
            equalizer.setEnabled(isEqualizerEnabled);
            bassBoost.setEnabled(isEqualizerEnabled);
            virtualizer.setEnabled(isEqualizerEnabled);

            // 设置均衡器预设
            setupPresets();

            // 设置均衡器滑块
            setupBandControls();

            // 设置低音增强
            setupBassBoost();

            // 设置虚拟环绕声
            setupVirtualizer();

            // 设置重置按钮
            btnResetEqualizer.setOnClickListener(v -> resetEqualizer());

            // 设置均衡器开关监听器
            switchEqualizer.setOnCheckedChangeListener((buttonView, isChecked) -> {
                isEqualizerEnabled = isChecked;
                preferences.edit().putBoolean(PREF_EQUALIZER_ENABLED, isChecked).apply();
                equalizer.setEnabled(isChecked);
                bassBoost.setEnabled(isChecked);
                virtualizer.setEnabled(isChecked);
                updateEqualizerUI(isChecked);
            });

            // 更新UI状态
            updateEqualizerUI(isEqualizerEnabled);

        } catch (Exception e) {
            e.printStackTrace();
            showToast("初始化均衡器失败: " + e.getMessage());
        }
    }

    private void setupPresets() {
        // 获取预设数量
        short numberOfPresets = equalizer.getNumberOfPresets();
        List<String> presetNames = new ArrayList<>();

        // 添加预设名称
        for (short i = 0; i < numberOfPresets; i++) {
            presetNames.add(equalizer.getPresetName(i));
        }
        presetNames.add(getString(R.string.custom)); // 添加自定义预设

        // 设置预设适配器
        ArrayAdapter<String> adapter = new ArrayAdapter<>(requireContext(),
                android.R.layout.simple_spinner_item, presetNames);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerPresets.setAdapter(adapter);

        // 设置当前预设
        if (currentPreset < numberOfPresets) {
            spinnerPresets.setSelection(currentPreset);
            equalizer.usePreset((short) currentPreset);
        } else {
            spinnerPresets.setSelection(numberOfPresets); // 自定义预设
            loadCustomPreset();
        }

        // 设置预设选择监听器
        spinnerPresets.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position < numberOfPresets) {
                    // 使用预设
                    equalizer.usePreset((short) position);
                    currentPreset = position;
                    preferences.edit().putInt(PREF_EQUALIZER_PRESET, position).apply();
                    updateBandLevels();
                } else {
                    // 使用自定义预设
                    currentPreset = position;
                    preferences.edit().putInt(PREF_EQUALIZER_PRESET, position).apply();
                    loadCustomPreset();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    private void setupBandControls() {
        // 获取频段数量
        short numberOfBands = equalizer.getNumberOfBands();
        customBandLevels = new short[numberOfBands];

        // 清除容器
        equalizerContainer.removeAllViews();

        // 获取均衡器范围
        final short minEQLevel = equalizer.getBandLevelRange()[0];
        final short maxEQLevel = equalizer.getBandLevelRange()[1];

        // 为每个频段创建控制器
        for (short i = 0; i < numberOfBands; i++) {
            final short band = i;

            // 创建垂直布局
            LinearLayout bandLayout = new LinearLayout(requireContext());
            bandLayout.setOrientation(LinearLayout.VERTICAL);
            bandLayout.setLayoutParams(new LinearLayout.LayoutParams(
                    0, LinearLayout.LayoutParams.MATCH_PARENT, 1));
            bandLayout.setGravity(Gravity.CENTER);

            // 创建频率文本
            TextView tvFreq = new TextView(requireContext());
            int frequency = equalizer.getCenterFreq(band) / 1000;
            tvFreq.setText((frequency < 1000) ? frequency + " Hz" : (frequency / 1000) + " kHz");
            tvFreq.setGravity(Gravity.CENTER);
            tvFreq.setLayoutParams(new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT));

            // 创建垂直SeekBar
            VerticalSeekBar seekBar = new VerticalSeekBar(requireContext());
            seekBar.setLayoutParams(new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    0, 1));
            seekBar.setMax(maxEQLevel - minEQLevel);
            seekBar.setProgress(equalizer.getBandLevel(band) - minEQLevel);

            // 创建级别文本
            TextView tvLevel = new TextView(requireContext());
            tvLevel.setText((equalizer.getBandLevel(band) / 100) + " dB");
            tvLevel.setGravity(Gravity.CENTER);
            tvLevel.setLayoutParams(new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT));

            // 设置SeekBar监听器
            seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    short bandLevel = (short) (progress + minEQLevel);
                    if (fromUser) {
                        equalizer.setBandLevel(band, bandLevel);
                        tvLevel.setText((bandLevel / 100) + " dB");
                        
                        // 保存自定义设置
                        customBandLevels[band] = bandLevel;
                        saveCustomPreset();
                        
                        // 如果不是自定义预设，切换到自定义预设
                        if (currentPreset != equalizer.getNumberOfPresets()) {
                            currentPreset = equalizer.getNumberOfPresets();
                            spinnerPresets.setSelection(currentPreset);
                            preferences.edit().putInt(PREF_EQUALIZER_PRESET, currentPreset).apply();
                        }
                    }
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {
                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                }
            });

            // 添加到布局
            bandLayout.addView(tvFreq);
            bandLayout.addView(seekBar);
            bandLayout.addView(tvLevel);
            equalizerContainer.addView(bandLayout);
        }
    }

    private void setupBassBoost() {
        // 设置低音增强
        bassBoost.setStrength(bassBoostStrength);
        seekBarBassBoost.setMax(1000);
        seekBarBassBoost.setProgress(bassBoostStrength);

        seekBarBassBoost.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    bassBoostStrength = (short) progress;
                    bassBoost.setStrength(bassBoostStrength);
                    preferences.edit().putInt(PREF_BASS_BOOST, bassBoostStrength).apply();
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
    }

    private void setupVirtualizer() {
        // 设置虚拟环绕声
        virtualizer.setStrength(virtualizerStrength);
        seekBarVirtualizer.setMax(1000);
        seekBarVirtualizer.setProgress(virtualizerStrength);

        seekBarVirtualizer.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    virtualizerStrength = (short) progress;
                    virtualizer.setStrength(virtualizerStrength);
                    preferences.edit().putInt(PREF_VIRTUALIZER, virtualizerStrength).apply();
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
    }

    private void updateBandLevels() {
        short numberOfBands = equalizer.getNumberOfBands();
        short minEQLevel = equalizer.getBandLevelRange()[0];

        for (short i = 0; i < numberOfBands; i++) {
            if (i < equalizerContainer.getChildCount()) {
                LinearLayout bandLayout = (LinearLayout) equalizerContainer.getChildAt(i);
                if (bandLayout.getChildCount() >= 3) {
                    VerticalSeekBar seekBar = (VerticalSeekBar) bandLayout.getChildAt(1);
                    TextView tvLevel = (TextView) bandLayout.getChildAt(2);
                    
                    short bandLevel = equalizer.getBandLevel(i);
                    seekBar.setProgress(bandLevel - minEQLevel);
                    tvLevel.setText((bandLevel / 100) + " dB");
                    
                    // 更新自定义预设数据
                    customBandLevels[i] = bandLevel;
                }
            }
        }
    }

    private void loadCustomPreset() {
        short numberOfBands = equalizer.getNumberOfBands();
        
        for (short i = 0; i < numberOfBands; i++) {
            short bandLevel = (short) preferences.getInt(PREF_CUSTOM_BANDS + i, 0);
            customBandLevels[i] = bandLevel;
            equalizer.setBandLevel(i, bandLevel);
        }
        
        updateBandLevels();
    }

    private void saveCustomPreset() {
        short numberOfBands = equalizer.getNumberOfBands();
        SharedPreferences.Editor editor = preferences.edit();
        
        for (short i = 0; i < numberOfBands; i++) {
            editor.putInt(PREF_CUSTOM_BANDS + i, customBandLevels[i]);
        }
        
        editor.apply();
    }

    private void resetEqualizer() {
        // 重置均衡器
        equalizer.usePreset((short) 0);
        currentPreset = 0;
        spinnerPresets.setSelection(0);
        preferences.edit().putInt(PREF_EQUALIZER_PRESET, 0).apply();
        
        // 重置低音增强
        bassBoostStrength = 0;
        bassBoost.setStrength(bassBoostStrength);
        seekBarBassBoost.setProgress(0);
        preferences.edit().putInt(PREF_BASS_BOOST, 0).apply();
        
        // 重置虚拟环绕声
        virtualizerStrength = 0;
        virtualizer.setStrength(virtualizerStrength);
        seekBarVirtualizer.setProgress(0);
        preferences.edit().putInt(PREF_VIRTUALIZER, 0).apply();
        
        // 更新UI
        updateBandLevels();
    }

    private void updateEqualizerUI(boolean enabled) {
        spinnerPresets.setEnabled(enabled);
        for (int i = 0; i < equalizerContainer.getChildCount(); i++) {
            ViewGroup bandLayout = (ViewGroup) equalizerContainer.getChildAt(i);
            for (int j = 0; j < bandLayout.getChildCount(); j++) {
                View view = bandLayout.getChildAt(j);
                view.setEnabled(enabled);
            }
        }
        seekBarBassBoost.setEnabled(enabled);
        seekBarVirtualizer.setEnabled(enabled);
        btnResetEqualizer.setEnabled(enabled);
    }

    private void releaseEqualizer() {
        if (equalizer != null) {
            equalizer.release();
            equalizer = null;
        }
        if (bassBoost != null) {
            bassBoost.release();
            bassBoost = null;
        }
        if (virtualizer != null) {
            virtualizer.release();
            virtualizer = null;
        }
    }

    private void showToast(String message) {
        Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show();
    }
} 